<template>
  <view class="container">
    <!-- 头部搜索区 -->
    <view class="search-bar">
      <view class="search-box" @tap="toSearchPage">
        <image src="@/static/images/icon/search.png" class="search-img" />
        <text class="sear-input">
          搜索您想要的商品
        </text>
      </view>
      <!-- 消息播放 -->
      <view v-if="news && news.length > 0" class="message-play">
        <up-notice-bar direction="column" :text="news" @click="onNewsPage"></up-notice-bar>
      </view>
    </view>
    <!-- 滚动内容区 -->
    <view class="main">
      <!-- 左侧菜单start -->
      <scroll-view scroll-y="true" class="leftmenu">
        <block v-for="(item, index) in categoryList" :key="item.categoryId">
          <view :class="'menu-item ' + (setCategoryId == item.categoryId ? 'active' : '') + ' '" :data-index="index"
            :data-id="item.categoryId" @tap="onMenuTab">
            {{ item.categoryName }}
          </view>
        </block>
        <view v-if="!categoryList || !categoryList.length" class="ca-empty">
          {{ categoryList && categoryList.length ? '该分类下暂无商品' : '暂无商品' }}
        </view>
      </scroll-view>
      <!-- 左侧菜单end -->

      <!-- 右侧内容start -->
      <!-- <scroll-view scroll-y="true" class="rightcontent">
        <view class="adver-map">
          <view class="item-a">
            <image :src="util.checkFileUrl(categoryImg)" mode="widthFix" />
          </view>
        </view>

        <view v-if="subCategoryList.length" class="th-cate-con">
          <block v-for="(thCateItem, index) in subCategoryList" :key="index">
            <view class="sub-category">
              <view class="sub-category-item" :data-categoryid="thCateItem.categoryId"
                :data-parentid="thCateItem.parentId" @tap="toCatePage">
                <image :src="util.checkFileUrl(thCateItem.pic)" class="more-pic" mode="widthFix" />
                <text>{{ thCateItem.categoryName }}</text>
              </view>
            </view>
          </block>
        </view>
        <view v-else class="cont-item empty">
          该分类下暂无子分类~
        </view>
      </scroll-view> -->
      <view class="rightcontent">
        <view v-for="(item, index) in categoryList" :id="'category' + item.categoryId" :key="item.categoryId">
          <view>
            <!-- <view>{{ item.categoryName }}</view> -->
            <image :src="util.checkFileUrl(item.pic)" mode="widthFix" />

            <view class="prod-show">
              <block v-for="(prod, index2) in prods[item.categoryId]" :key="prod.prodId">
                <view class="show-item" :data-prodid="prod.prodId" @tap="toProdPage">
                  <view class="more-prod-pic">
                    <image class="item-pic" :src="prod.pic" alt="" />
                  </view>
                  <view class="prod-text-right">
                    <view class="prod-text more">
                      {{ prod.prodName }}
                    </view>
                    <view class="prod-info">
                      {{ prod.brief }}
                    </view>
                    <view class="b-cart">
                      <view class="price">
                        <text class="symbol">
                          ￥
                        </text>
                        <text class="big-num">
                          {{ prod.price }}
                        </text>
                      </view>
                      <image src="@/static/images/tabbar/basket-sel.png" class="basket-img"
                        @tap.stop="addToCart(prod)" />
                    </view>
                  </view>
                </view>
              </block>
            </view>

          </view>
        </view>
      </view>
      <!-- 右侧内容end -->
    </view>
  </view>
</template>

<script setup>
import { onUnload, onLoad } from '@dcloudio/uni-app'
import { getCurrentInstance } from 'vue';
import util from '@/utils/util.js'

const instance = getCurrentInstance()

const categoryList = ref([])
const subCategoryList = ref([])
const news = ref([]);
const categoryRefList = ref({});
const setCategoryId = ref(null);
const prods = ref({});
/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  // 加载分类列表
  http.request({
    url: '/category/categoryInfo',
    method: 'GET',
    data: {
      parentId: ''
    }
  })
    .then(({ data }) => {
      categoryList.value = data
      setCategoryId.value = categoryList.value[0].categoryId
    })

  http.request({
    url: '/prod/getAllProd',
    method: 'GET',
    data: {
      shopId: '1'
    }
  })
    .then(({ data }) => {
      console.log(data, 'data');
      // 分类
      const targetObj = {}
      data.forEach(item => {
        if (targetObj[item.categoryId]) {
          targetObj[item.categoryId].push(item)
        } else {
          targetObj[item.categoryId] = [item]
        }
      })
      prods.value = targetObj;
    })
  getNoticeList();
})

/**
 * 分类点击事件
 */
const onMenuTab = (e) => {
  const id = e.currentTarget.dataset.id
  setCategoryId.value = id
  uni.createSelectorQuery().in(instance).select('#category' + id).boundingClientRect((rect) => {
    // 使用scrollIntoView方法滚动到目标元素
    uni.pageScrollTo({
      scrollTop: rect.top,
      duration: 200
    })
  }).exec();
}

/**
 * 跳转搜索页
 */
const toSearchPage = () => {
  uni.navigateTo({
    url: '/pages/search-page/search-page'
  })
}


/**
 * 跳转子分类商品页面
 */
const toCatePage = (e) => {
  const { categoryid } = e.currentTarget.dataset
  // uni.navigateTo({
  //   url: `/pages/sub-category/sub-category?parentId=${parentId.value}&categoryId=${categoryid}`
  // })
}

const getNoticeList = () => {
  // 加载公告
  http.request({
    url: '/shop/notice/topNoticeList',
    method: 'GET',
    data: {}
  })
    .then(({ data }) => {
      news.value = data && data.map(i => i.title)
    })
}

/**
 * 跳转公告列表页面
 */
const onNewsPage = () => {
  uni.navigateTo({
    url: '/pages/recent-news/recent-news'
  })
}

//滚动监听
const watchScroll = ($event) => {
  const target = $event.target;
  const scrollTop = target ? target.scrollTop : 0;
  const maxObj = {
    offsetTop: 9999,
    id: ''
  }
  for (const id in categoryRefList.value) {
    const _offsetTop = categoryRefList.value[id].offsetTop;
    if (_offsetTop >= scrollTop && _offsetTop <= maxObj.offsetTop) {
      maxObj.offsetTop = _offsetTop
      maxObj.id = id
    }
  }
}

const toProdPage = (e) => {
  const prodid = e.currentTarget.dataset.prodid

  if (prodid) {
    uni.navigateTo({
      url: '/pages/prod/prod?prodid=' + prodid
    })
  }
}

/**
 * 加入购物车
 * @param item
 */
const addToCart = (item) => {
  uni.showLoading({
    mask: true
  })
  http.request({
    url: '/prod/prodInfo',
    method: 'GET',
    data: {
      prodId: item.prodId
    }
  })
    .then(({ data }) => {
      http.request({
        url: '/p/shopCart/changeItem',
        method: 'POST',
        data: {
          basketId: 0,
          count: 1,
          prodId: data.prodId,
          shopId: data.shopId,
          skuId: data.skuList[0].skuId
        }
      })
        .then(() => {
          uni.hideLoading()
          http.getCartCount() // 重新计算购物车总数量
          uni.showToast({
            title: '加入购物车成功',
            icon: 'none'
          })
        })
    })
}

</script>

<style scoped lang="scss">
@import "./category.scss";
</style>
